﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HuntingFishGame.ManageDomain.BLL.WeChat;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace HuntingFishGame.H5.Controllers
{
    public class QRCodeFormController : Controller
    {
        private readonly string access_token = WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue;
        string result = "";
        // GET: QRCodeForm
        public ActionResult Index()
        {
            Helper.ExtLog(" 接收到参数数据：" + Request.Params["code"]);

            //获取并判断客户端发送过来的参数
            if (Request.Params["code"] != null)
            {
                string str = CreateTicket(Request.Params["code"].ToString());
                if (str != "" && str.Substring(str.Length - 1, 1) == "_")
                {
                    str = str.Substring(0, str.Length - 1);
                }

                str = GetTicketImage(str);
                Helper.ExtLog(" 二维码数据：" + str);

                string imageUrl = string.Empty;
                if (Session["imgname"] != null && Session["imgname"].ToString() != "")
                {
                    imageUrl = "image/temp/" + Session["imgname"].ToString();
                }
                else
                {
                    imageUrl = str;
                }
                ViewData["imageUrl"] = imageUrl;
            }

            return View();
        }

        #region 创建二维码ticket
        /// <summary> 
        /// 创建二维码ticket 
        /// </summary> 
        /// <returns></returns> 
        public string CreateTicket(string code)
        {
            string strJson = @"{""expire_seconds"": 604800, ""action_name"": ""QR_LIMIT_STR_SCENE"", ""action_info"": {""scene"": {""scene_str"":""" + code + @"""}}}";
            string wxurl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;//GetCode.Code

            Helper.ExtLog(" access_token验证url：" + wxurl.ToString());
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            try
            {
                result = myWebClient.UploadString(wxurl, "POST", strJson);

                if (result.Contains("errcode"))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                    Helper.ExtLog(" 错误数据：" + jo.ToString());
                    if (jo["errcode"] != null && (jo["errcode"].ToString() == "42001" || jo["errcode"].ToString() == "40001"))
                    {
                        //如果 access_token 超时，或者无效，进行再次申请获取
                        //GetCode getCode = new GetCode();
                        //getCode.GetCodeValue();
                        CreateTicket(access_token);//Request.Params["code"].ToString()
                    }
                    else if (jo["errcode"] != null && jo["errcode"].ToString() == "0")
                    {
                        //接收到微信的内容
                        Ticket1 _mode = JsonHelper.FromJson<Ticket1>(result);
                        result = _mode.ticket;
                        result = _mode.ticket + "_" + _mode.expire_seconds;
                    }
                }
                else
                {
                    //接收到微信的内容
                    Ticket1 _mode = JsonHelper.FromJson<Ticket1>(result);
                    result = _mode.ticket;
                    result = _mode.ticket + "_" + _mode.expire_seconds;
                }
            }
            catch (Exception ex)
            {
                result = "Error:" + ex.Message;
            }
            return result;
        }
        #endregion

        public string GetTicketImage(string TICKET)
        {
            string content = string.Empty;
            string strpath = string.Empty;
            string savepath = string.Empty;
            string stUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + Server.UrlEncode(TICKET);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);
            req.Method = "GET";
            try
            {
                using (WebResponse wr = req.GetResponse())
                {
                    HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
                    strpath = myResponse.ResponseUri.ToString();

                    WebClient mywebclient = new WebClient();
                    savepath = Server.MapPath("image") + "\\temp\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + "." + myResponse.ContentType.Split('/')[1].ToString();
                    Session["imgname"] = DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + "." + myResponse.ContentType.Split('/')[1].ToString();
                    try
                    {
                        mywebclient.DownloadFile(strpath, savepath);
                    }
                    catch (Exception ex)
                    {
                        savepath = ex.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                savepath = e.ToString();
            }
            return strpath.ToString();
        }
    }
    #region 转换二维码
    /// <summary>
    /// 转换二维码
    /// </summary>
    public class Ticket1
    {
        public Ticket1()
        { }

        string _expire_seconds;

        /// <summary> 
        /// 获取的二维码ticket，凭借此ticket可以在有效时间内换取二维码。 
        /// </summary> 
        string _ticket;
        public string ticket
        {
            get { return _ticket; }
            set { _ticket = value; }
        }

        /// <summary> 
        /// 凭证有效时间，单位：秒 
        /// </summary> 
        public string expire_seconds
        {
            get { return _expire_seconds; }
            set { _expire_seconds = value; }
        }
    }
    #endregion
}